package com.blog.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blog.entity.Article;
import com.blog.entity.Category;
import com.blog.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * code
 *
 * @author: garyme
 * @date: 2025/3/25 13:57
 * @description:
 */
@RestController
@RequestMapping("/api/categories")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @GetMapping
    public ResponseEntity<Page<Category>> listCategories(@RequestParam(defaultValue = "1") Integer pageNum,
                                                         @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<Category> articlePage = categoryService.listCategorys(pageNum, pageSize);
        return ResponseEntity.ok(articlePage);
    }
    @PostMapping
    public ResponseEntity<String> addCategory(@RequestBody Category category) {
        categoryService.save(category);
        return ResponseEntity.ok("添加成功");
    }
    @PutMapping("/{id}")
    public ResponseEntity<String> updateCategory(@PathVariable Long id, @RequestBody Category category) {
        category.setId(id);
        categoryService.updateById(category);
        return ResponseEntity.ok("修改成功");
    }
    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteCategory(@PathVariable Long id) {
        categoryService.removeById(id);
        return ResponseEntity.ok("删除成功");
    }
    @GetMapping("/index")
    public ResponseEntity<List<Category>> listCategoriesForIndex() {
        List<Category> categories = categoryService.list().stream().limit(4).collect(Collectors.toList());
        return ResponseEntity.ok(categories);
    }

}
